package com.nebula.salary.portal.config.security.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nebula.salary.common.constants.Const;
import com.nebula.salary.common.constants.ReturnMessage;
import com.nebula.salary.common.result.ResponseCode;
import com.nebula.salary.common.result.ServerResponse;
import com.nebula.salary.common.utils.JwtTokenUtil;
import com.nebula.salary.model.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 成功退出处理实现类
 *
 * @author codex
 * @since 2022-02-11
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    
        response.setCharacterEncoding(Const.DEFAULT_CHARACTER_ENCODING);
        response.setContentType(Const.CONTENT_TYPE_JSON);
    
        LoginUser loginUser = jwtTokenUtil.getLoginUser(request);
        if (loginUser != null) {
            // 删除用户在redis中的缓存
            jwtTokenUtil.delLoginUser(loginUser.getUuid());
        }
    
        PrintWriter writer = response.getWriter();
    
        writer.write(new ObjectMapper().writeValueAsString(ServerResponse.createBySuccessCodeMessge(ResponseCode.LOGOUT_SUCCESS.getCode(), ReturnMessage.LOGOUT_SUCCESS)));
    
        writer.flush();
        writer.close();
    }
}
